package com.example.ibsp_demo.controller.create;

import com.example.ibsp_demo.mapper.content.*;
import com.example.ibsp_demo.pojo.entity.content.*;
import com.example.ibsp_demo.pojo.response.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/create")
@CrossOrigin(origins = "http://localhost:8080")
public class CreateController {

    @Value("${file.upload.path}")
    private String uploadPath;

    @Autowired
    private DraftMapper draftMapper;

    @Autowired
    private ContentMapper contentMapper;

    @Autowired
    private ContentTagMapper contentTagMapper;

    @Autowired
    private LikeMapper likeMapper;

    @Autowired
    private CommentMapper commentMapper;

    // 发布内容（草稿转正式内容）
    @PostMapping("/publish")
    public ResponseMessage<String> publishDraft(@RequestParam Integer draftId) {
        try {
            Draft draft = draftMapper.selectByDraftId(draftId);
            if (draft == null) {
                return ResponseMessage.error(5001, "草稿不存在");
            }

            // 检查是否已经提交过
            if (draft.getIsSubmit() != null && draft.getIsSubmit() == 1) {
                return ResponseMessage.error(5004, "该草稿已提交，不能重复提交");
            }

            Content content = new Content();
            content.setAuid(draft.getUid());
            content.setTitle(draft.getTitle());
            content.setContent(draft.getContentText());
            content.setCover(draft.getCoverImage());
            content.setPid(1); // 默认分区
            content.setPublishTime(LocalDateTime.now());
            content.setStatus(0); // 待审核

            contentMapper.insert(content);

            Integer ctid = content.getCtid();
            if (ctid == null) {
                return ResponseMessage.error(5002, "内容插入失败");
            }

            try {
                List<String> tags = parseTags(draft.getTagIds());
                for (String tag : tags) {
                    ContentTag contentTag = new ContentTag();
                    contentTag.setCtid(ctid);
                    contentTag.setTagName(tag);
                    contentTagMapper.insert(contentTag);
                }
            } catch (IllegalArgumentException e) {
                return ResponseMessage.error(5003, e.getMessage());
            }

            // 标记草稿为已提交
            draftMapper.markAsSubmit(draftId);

            return ResponseMessage.success("发布成功");

        } catch (Exception e) {
            e.printStackTrace(); // 打印异常信息
            return ResponseMessage.error(500, "服务器内部错误: " + e.getMessage());
        }
    }


    // 点赞
    @PostMapping("/like")
    public ResponseMessage<String> likeContent(@RequestParam Integer likerId, @RequestParam Integer ctid) {
        // 判断是否已点赞
        Like existing = likeMapper.selectByLikerAndCtid(likerId, ctid);
        if (existing != null) {
            return ResponseMessage.error(500, "您已点赞过该内容");
        }

        Like like = new Like();
        like.setLikerId(likerId);
        like.setCtid(ctid);
        like.setLikeTime(LocalDateTime.now());
        likeMapper.like(like);

        // 更新 content 表的点赞数
        contentMapper.updateLikeCount(ctid, 1); // +1

        return ResponseMessage.success("点赞成功");
    }

    //取消点赞
    @PostMapping("/unlike")
    public ResponseMessage<String> unlikeContent(@RequestParam Integer likerId, @RequestParam Integer ctid) {
        likeMapper.cancelLikeByLikerAndCtid(likerId, ctid);
        contentMapper.updateLikeCount(ctid, -1); // 减少点赞数
        return ResponseMessage.success("取消点赞成功");
    }


    // 解析标签
    private List<String> parseTags(String input) throws IllegalArgumentException {
        List<String> tags = new ArrayList<>();
        if (input == null || input.isEmpty()) return tags;

        // 校验是否以 # 开头
        if (!input.startsWith("#")) {
            throw new IllegalArgumentException("标签格式错误：必须以 # 开头");
        }

        // 校验是否包含连续的 ##（不允许连续标签符号）
        if (input.contains("##")) {
            throw new IllegalArgumentException("标签格式错误：不能包含连续的 ##");
        }

        // 分割标签（不管是否以 # 结尾）
        String[] split = input.split("#");

        // 跳过第一个空字符串（因为以 # 开头）
        for (int i = 1; i < split.length; i++) {
            String tag = split[i].trim();
            if (!tag.isEmpty()) {
                tags.add(tag);
            }
        }

        return tags;
    }

    @PostMapping("/uploadCover")
    public ResponseMessage<Map<String, String>> uploadCover(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseMessage.error(500, "文件为空");
        }

        try {
            // 构建上传路径
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 保存文件
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            String filePath = uploadPath + File.separator + fileName;

            file.transferTo(new File(filePath));

            // 关键修复：将路径中的反斜杠替换为正斜杠
            String fileUrl = filePath.replace("\\", "/");

            Map<String, String> result = new HashMap<>();
            result.put("url", fileUrl); // 返回格式化后的路径（全正斜杠）

            return ResponseMessage.success(result);

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseMessage.error(500, "上传失败：" + e.getMessage());
        }
    }

    @GetMapping("/content/detail")
    public ResponseMessage<Content> getContentDetail(@RequestParam Integer ctid) {
        try {
            Content content = contentMapper.selectByCtid(ctid);
            if (content == null) {
                return ResponseMessage.error(404, "内容不存在");
            }
            // 补充标签信息
            List<ContentTag> tags = contentTagMapper.selectByCtid(ctid);
            content.setTags(tags);
            return ResponseMessage.success(content);
        } catch (Exception e) {
            return ResponseMessage.error(500, "获取内容详情失败: " + e.getMessage());
        }
    }

}
